package com.xfp.interceptor;


import com.xfp.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(1==1)
            return true;
        log.info("拦截器启动...");
        String token = request.getHeader("Authorization");
        log.info("接收到的token为：{}",token);

        if(!StringUtils.hasLength(token)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        try {
            JwtUtil.parseJWT(token);
            log.info("token解析成功");
            return true;
        } catch (Exception e) {
            log.info("token解析失败");
            log.info("token异常为: {}",e);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }
}